package cn.springboot.erp.shiro;

import cn.springboot.erp.filter.WebTokenFilter;
import org.apache.shiro.realm.Realm;
import org.apache.shiro.spring.web.ShiroFilterFactoryBean;
import org.apache.shiro.web.mgt.DefaultWebSecurityManager;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

import javax.servlet.Filter;
import java.util.HashMap;
import java.util.LinkedHashMap;

@Configuration
public class ShiroWebConfig {

    // 托管Realm域对象
    @Bean
    public CustomerRealm customerRealm(){
        return new CustomerRealm();
    }

    // 托管默认的安全管理器
    @Bean
    public DefaultWebSecurityManager defaultWebSecurityManager(Realm realm){
        DefaultWebSecurityManager defaultWebSecurityManager = new DefaultWebSecurityManager();
        defaultWebSecurityManager.setRealm(realm);

        return defaultWebSecurityManager;
    }

    @Bean
    public ShiroFilterFactoryBean shiroFilterFactoryBean(DefaultWebSecurityManager defaultWebSecurityManager){
        ShiroFilterFactoryBean shiroFilterFactoryBean = new ShiroFilterFactoryBean();
        shiroFilterFactoryBean.setSecurityManager(defaultWebSecurityManager);

        // 设置自定义拦截器
        HashMap<String, Filter> filterHashMap = new HashMap<>();
        filterHashMap.put("customer",new WebTokenFilter());
        shiroFilterFactoryBean.setFilters(filterHashMap);

        //设置拦截规则
        LinkedHashMap<String, String> linkedHashMap = new LinkedHashMap<>();
        linkedHashMap.put("/user/login","anon");
        linkedHashMap.put("/code/getCode","anon");
        linkedHashMap.put("/**","customer");
        shiroFilterFactoryBean.setFilterChainDefinitionMap(linkedHashMap);
        shiroFilterFactoryBean.setLoginUrl("/login");
        return shiroFilterFactoryBean;
    }
}
